package com.atguigu.tingshu.album.api;

import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.common.result.Result;
import io.minio.*;
import io.minio.errors.MinioException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Tag(name = "上传管理接口")
@RestController
@RequestMapping("api/album")
public class FileUploadApiController {

    @Autowired
    private MinioConstantProperties minioConstantProperties;

    //  前提条件这个类必须被spring 容器扫描.
    //    @Value("${minio.endpointUrl}") + @RefreshScope 才能实现动态刷新！ nacos
    //    private String endpointUrl;



    //  http://127.0.0.1/api/album/fileUpload
    /*
    <from action="" method="" format="">
        <input type="file" name="file">
    </from>
     */
    //  获取请求的方式：springmvc 框架中有一个类 MultipartFile 这个对象名file 应该与表单提交过来的名称一致！
    @Operation(summary = "文件上传")
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file){
        //  返回文件上传之后的地址;
        String url = "";
        //  利用文件服务器来存储上传的图片,并获取到文件上传的地址.
        //  分布式文件存储系统：OSS-阿里 ，fastDFS-余庆， Minio-本地自己搭建；开源，免费，丢失N/2磁盘的情况下，依然能够找回数据。纠删码--一种数据算法【高度冗余】
        try {
            // Create a minioClient with the MinIO server playground, its access key and secret key.
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioConstantProperties.getEndpointUrl())
                            .credentials(minioConstantProperties.getAccessKey(), minioConstantProperties.getSecreKey())
                            .build();

            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConstantProperties.getBucketName()).build());
            } else {
                System.out.println("Bucket "+minioConstantProperties.getBucketName()+" already exists.");
            }

            //  文件名称：不能重复！uuid.jpg
            //  必须要获取到原上传文件的后缀名. 先获取文件名.
            //  atguigu.jpg;
            String originalFilename = file.getOriginalFilename();
//            originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
            //  文件上传.
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(minioConstantProperties.getBucketName()).object(fileName).stream(
                                    file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            //  获取到文件上传的url地址：
            //  //img10.360buyimg.com/n7/jfs/t1/210393/27/40584/78408/6612d55bFdbcf3eaf/cc4348a591e14aaf.jpg
            //  http://192.168.200.130:9000/atguigutingshu/fileName;
            url = minioConstantProperties.getEndpointUrl()+"/"+minioConstantProperties.getBucketName()+"/"+fileName;
            System.out.println("url:\t"+url);
        } catch (MinioException e) {
            System.out.println("Error occurred: " + e);
            System.out.println("HTTP trace: " + e.httpTrace());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        //  返回文件上传地址；
        return Result.ok(url);
    }

    public static void main(String[] args) {
        String originalFilename = "atguigu.jpg";
        System.out.println(FilenameUtils.getExtension(originalFilename));
        System.out.println(originalFilename.substring(originalFilename.lastIndexOf(".")));
    }



}
